import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { motivationApi } from '@/api'
import type {
    DailyChallenge,
    UserDailyChallenge,
    SocialEnergyContent,
    Achievement,
    UserNotification,
    UserTier
} from '@/types'

export const useMotivationStore = defineStore('motivation', () => {
    // 状态
    const dailyChallenges = ref<DailyChallenge[]>([])
    const userDailyChallenges = ref<UserDailyChallenge[]>([])
    const socialEnergyContent = ref<SocialEnergyContent[]>([])
    const achievements = ref<Achievement[]>([])
    const userAchievements = ref<Achievement[]>([])
    const notifications = ref<UserNotification[]>([])
    const userTier = ref<UserTier | null>(null)
    const tierHistory = ref<UserTier[]>([])
    const motivationStats = ref({
        consecutiveDays: 0,
        totalChallengesCompleted: 0,
        totalAchievementsUnlocked: 0,
        currentStreak: 0,
        energyLevel: 0
    })
    const loading = ref(false)

    // 计算属性
    const todayChallenges = computed(() => {
        const today = new Date().toISOString().split('T')[0]
        return userDailyChallenges.value.filter(challenge =>
            challenge.challengeDate === today
        )
    })

    const completedTodayChallenges = computed(() => {
        return todayChallenges.value.filter(challenge => challenge.isCompleted)
    })

    const todayProgress = computed(() => {
        const total = todayChallenges.value.length
        const completed = completedTodayChallenges.value.length
        return total > 0 ? Math.round((completed / total) * 100) : 0
    })

    const unreadNotifications = computed(() => {
        return notifications.value.filter(notification => !notification.isRead)
    })

    const unreadNotificationCount = computed(() => {
        return unreadNotifications.value.length
    })

    const unlockedAchievements = computed(() => {
        return userAchievements.value.filter(achievement => achievement.isUnlocked)
    })

    const availableAchievements = computed(() => {
        return achievements.value.filter(achievement => !achievement.isUnlocked)
    })

    // 获取今日挑战
    async function fetchTodayChallenge() {
        try {
            loading.value = true
            const challenge = await motivationApi.getTodayChallenge()
            // 将单个挑战添加到数组中
            const today = new Date().toISOString().split('T')[0] || ''

            const userChallenge: UserDailyChallenge = {
                challengeId: challenge.id,
                userId: 0, // 将由API返回
                challengeDate: today,
                isCompleted: challenge.isCompleted,
                progress: challenge.isCompleted ? 100 : 0
            }

            // 只有当 completedAt 存在时才设置
            if (challenge.completedAt) {
                userChallenge.completedAt = challenge.completedAt
            }

            // 更新或添加今日挑战
            const existingIndex = userDailyChallenges.value.findIndex(
                c => c.challengeId === challenge.id && c.challengeDate === today
            )

            if (existingIndex > -1) {
                userDailyChallenges.value[existingIndex] = userChallenge
            } else {
                userDailyChallenges.value.push(userChallenge)
            }

            return challenge
        } catch (error) {
            console.error('Failed to fetch today challenge:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    // 完成今日挑战
    async function completeTodayChallenge(challengeId: number) {
        try {
            const result = await motivationApi.completeTodayChallenge(challengeId)

            // 更新本地状态
            const today = new Date().toISOString().split('T')[0]
            const challenge = userDailyChallenges.value.find(
                c => c.challengeId === challengeId && c.challengeDate === today
            )

            if (challenge) {
                challenge.isCompleted = true
                challenge.completedAt = new Date().toISOString()
                challenge.progress = 100
            }

            // 更新统计数据
            motivationStats.value.totalChallengesCompleted++

            return result
        } catch (error) {
            console.error('Failed to complete today challenge:', error)
            throw error
        }
    }

    // 获取每日挑战
    async function fetchDailyChallenges(date?: string) {
        try {
            loading.value = true
            const challenges = await motivationApi.getDailyChallenges(date)
            dailyChallenges.value = challenges
            return challenges
        } catch (error) {
            console.error('Failed to fetch daily challenges:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    // 获取用户每日挑战状态
    async function fetchUserDailyChallenges(userId: number, date?: string) {
        try {
            const challenges = await motivationApi.getUserDailyChallenges(userId, date)
            userDailyChallenges.value = challenges
            return challenges
        } catch (error) {
            console.error('Failed to fetch user daily challenges:', error)
            throw error
        }
    }

    // 完成每日挑战
    async function completeDailyChallenge(challengeId: number) {
        try {
            const response = await motivationApi.completeDailyChallenge(challengeId)

            // 更新本地状态
            const challenge = userDailyChallenges.value.find(c => c.challengeId === challengeId)
            if (challenge) {
                challenge.isCompleted = true
                challenge.completedAt = new Date().toISOString()
                challenge.rewardEarned = response.data?.rewardEarned
            }

            // 更新统计数据
            motivationStats.value.totalChallengesCompleted++

            return response
        } catch (error) {
            console.error('Failed to complete daily challenge:', error)
            throw error
        }
    }

    // 获取挑战历史
    async function fetchChallengeHistory() {
        try {
            loading.value = true
            const history = await motivationApi.getChallengeHistory()
            // 合并到现有数据中
            userDailyChallenges.value = [...userDailyChallenges.value, ...history]
            return history
        } catch (error) {
            console.error('Failed to fetch challenge history:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    // 获取所有成就
    async function fetchAllAchievements() {
        try {
            loading.value = true
            const achievementList = await motivationApi.getAllAchievements()
            achievements.value = achievementList
            return achievementList
        } catch (error) {
            console.error('Failed to fetch all achievements:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    // 获取用户成就
    async function fetchUserAchievements() {
        try {
            const achievementList = await motivationApi.getUserAchievements()
            userAchievements.value = achievementList
            return achievementList
        } catch (error) {
            console.error('Failed to fetch user achievements:', error)
            throw error
        }
    }

    // 获取社交能量站内容
    async function fetchSocialEnergyContent() {
        try {
            loading.value = true
            const content = await motivationApi.getSocialEnergyContent()
            socialEnergyContent.value = content
            return content
        } catch (error) {
            console.error('Failed to fetch social energy content:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    // 获取个性化鼓励内容
    async function fetchPersonalizedEncouragement(userId: number) {
        try {
            const encouragement = await motivationApi.getPersonalizedEncouragement(userId)
            return encouragement
        } catch (error) {
            console.error('Failed to fetch personalized encouragement:', error)
            throw error
        }
    }

    // 获取用户段位信息
    async function fetchUserTier() {
        try {
            const tier = await motivationApi.getUserTier()
            userTier.value = tier
            return tier
        } catch (error) {
            console.error('Failed to fetch user tier:', error)
            throw error
        }
    }

    // 获取段位历史
    async function fetchTierHistory() {
        try {
            const history = await motivationApi.getTierHistory()
            tierHistory.value = history
            return history
        } catch (error) {
            console.error('Failed to fetch tier history:', error)
            throw error
        }
    }

    // 领取成就奖励
    async function claimAchievementReward(achievementId: number) {
        try {
            const response = await motivationApi.claimAchievementReward(achievementId)

            // 更新本地成就状态
            const achievement = userAchievements.value.find(a => a.id === achievementId)
            if (achievement) {
                achievement.isUnlocked = true
            }

            return response
        } catch (error) {
            console.error('Failed to claim achievement reward:', error)
            throw error
        }
    }

    // 获取用户通知
    async function fetchNotifications(userId: number, params?: any) {
        try {
            const response = await motivationApi.getNotifications(userId, params)

            if (params?.page === 1 || !params?.page) {
                notifications.value = response.data
            } else {
                notifications.value.push(...response.data)
            }

            return response
        } catch (error) {
            console.error('Failed to fetch notifications:', error)
            throw error
        }
    }

    // 标记通知为已读
    async function markNotificationAsRead(notificationId: number) {
        try {
            await motivationApi.markNotificationAsRead(notificationId)

            // 更新本地状态
            const notification = notifications.value.find(n => n.id === notificationId)
            if (notification) {
                notification.isRead = true
            }
        } catch (error) {
            console.error('Failed to mark notification as read:', error)
            throw error
        }
    }

    // 标记所有通知为已读
    async function markAllNotificationsAsRead(userId: number) {
        try {
            await motivationApi.markAllNotificationsAsRead(userId)

            // 更新本地状态
            notifications.value.forEach(notification => {
                notification.isRead = true
            })
        } catch (error) {
            console.error('Failed to mark all notifications as read:', error)
            throw error
        }
    }

    // 获取用户激励统计数据
    async function fetchMotivationStats(userId: number) {
        try {
            const response = await motivationApi.getUserMotivationStats(userId)
            if (response.data) {
                motivationStats.value = response.data
            }
            return response.data
        } catch (error) {
            console.error('Failed to fetch motivation stats:', error)
            throw error
        }
    }

    // 添加新成就
    function addAchievement(achievement: Achievement) {
        userAchievements.value.push(achievement)
        motivationStats.value.totalAchievementsUnlocked++
    }

    // 添加新通知
    function addNotification(notification: UserNotification) {
        notifications.value.unshift(notification)
    }

    // 更新能量等级
    function updateEnergyLevel(level: number) {
        motivationStats.value.energyLevel = level
    }

    // 更新连续天数
    function updateConsecutiveDays(days: number) {
        motivationStats.value.consecutiveDays = days
        motivationStats.value.currentStreak = days
    }

    // 刷新今日数据
    async function refreshTodayData(userId: number) {
        const today = new Date().toISOString().split('T')[0]
        await Promise.all([
            fetchDailyChallenges(today),
            fetchUserDailyChallenges(userId, today),
            fetchSocialEnergyContent(),
            fetchMotivationStats(userId)
        ])
    }

    return {
        // 状态
        dailyChallenges,
        userDailyChallenges,
        socialEnergyContent,
        achievements,
        userAchievements,
        notifications,
        userTier,
        tierHistory,
        motivationStats,
        loading,

        // 计算属性
        todayChallenges,
        completedTodayChallenges,
        todayProgress,
        unreadNotifications,
        unreadNotificationCount,
        unlockedAchievements,
        availableAchievements,

        // 方法
        fetchTodayChallenge,
        completeTodayChallenge,
        fetchDailyChallenges,
        fetchUserDailyChallenges,
        completeDailyChallenge,
        fetchChallengeHistory,
        fetchAllAchievements,
        fetchUserAchievements,
        fetchSocialEnergyContent,
        fetchPersonalizedEncouragement,
        fetchUserTier,
        fetchTierHistory,
        claimAchievementReward,
        fetchNotifications,
        markNotificationAsRead,
        markAllNotificationsAsRead,
        fetchMotivationStats,
        addAchievement,
        addNotification,
        updateEnergyLevel,
        updateConsecutiveDays,
        refreshTodayData
    }
})